package com.hylanda.pb.service;

import java.util.Map;

import net.minidev.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.hylanda.pb.service.common.ConstantHelper;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;

/**
 * @author zhangy
 * @E-mail:blackoon88@gmail.com
 * @qq:846579287
 * @version created at：2018年1月19日 上午11:14:20 note
 */
@Service
public class PowerBiTokenService {

	public String genToken(Map<String, Object> map) {
		String wcn = (String) map.get("collectionName");
		String wid = (String) map.get("workspaceID");
		String rid = (String) map.get("reportID");
		String access_key = (String) map.get("access_key");
		String scp = (String) map.get("model");
		if (!StringUtils.isEmpty(wcn) && !StringUtils.isEmpty(wid)
				&& !StringUtils.isEmpty(rid)
				&& !StringUtils.isEmpty(access_key)
				&& !StringUtils.isEmpty(scp)) {
			JSONObject json = new JSONObject();
			// scp=Report.Read
			// scp=Report.ReadWrite
			// scp=Report.Read Workspace.Report.Create
			// scp=Report.ReadWrite Workspace.Report.Create
			// scp=Dataset.Read Workspace.Report.Create
			json.put("scp", scp);
			json.put("wcn", wcn);// 必须项
			json.put("wid", wid);// 必须项
			json.put("ver", ConstantHelper.ver);
			json.put("aud", ConstantHelper.aud);
			json.put("iss", ConstantHelper.iss);
			json.put("type", ConstantHelper.type);
			json.put("rid", rid);// reportID
			json.put("nbf", ConstantHelper.getCurrentTime());
			json.put("exp", ConstantHelper.getOneHourLaterTime());
			Payload payload = new Payload(json);
			JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
			header.setContentType("jwt");
			// Create JWS object
			JWSObject jwsObject = new JWSObject(header, payload);
			// Create HMAC signer
			JWSSigner signer = new MACSigner(access_key.getBytes());
			try {
				jwsObject.sign(signer);
			} catch (JOSEException e) {
				return null;
			}
			String token = jwsObject.serialize();
			return token;
		} else {
			return null;
		}
	}
}
